package com.shenmazong.servertalkadmin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shenmazong.pojo.TbSeller;
import com.shenmazong.servertalkadmin.mapper.TbSellerMapper;
import com.shenmazong.servertalkadmin.service.TbSellerService;
import com.shenmazong.utils.JwtTokenUtils;
import com.shenmazong.utils.ResponseResult;
import com.shenmazong.utils.StringTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TbSellerServiceImpl implements TbSellerService {
    @Autowired
    private TbSellerMapper tbSellerMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public ResponseResult addSellerUser(String mobile, String userName, String nickName, Integer sex, Integer age, Long saleFee, String address) {
        ResponseResult result=ResponseResult.SUCCESS();
        HashMap<String, Object> hashMap = new HashMap<>();
        //判断是否用户名是否重复
        TbSeller tbSeller = tbSellerMapper.selectOne(new QueryWrapper<TbSeller>()
                .eq("user_name", userName).last("limit 1"));
        if (tbSeller!=null){
            result.setFailMessage("销售已经存在");
            return  result;
        }
        tbSeller = new TbSeller();
        tbSeller.setUserName(userName);
        String salt = StringTools.getRandomString(32);
        tbSeller.setPassSalt(salt);

        String password = "123456" + "." + salt;
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        tbSeller.setUserPass(md5Password);

        tbSeller.setSaleFee(saleFee);
        tbSeller.setMobile(mobile);
        tbSeller.setNickName(nickName);
        tbSeller.setAge(age);
        tbSeller.setSex(sex);
        tbSeller.setAddress(address);

        //添加
        tbSellerMapper.insert( tbSeller);
        if ( tbSeller.getId() != null){
            tbSeller.setUserPass("");
            tbSeller.setPassSalt("");
            hashMap.put("seller", tbSeller);
            result.setResult(hashMap);
            return  result;
        }

        result.setFailMessage("销售添加失败");
        return  result;
    }

    @Override
    public ResponseResult delSellerUser(Integer id) {
        ResponseResult result=ResponseResult.SUCCESS();
        //判断销售是否存在
        TbSeller seller = tbSellerMapper.selectById(id);
        if (seller==null){
            result.setFailMessage("销售不存在");
            return  result;
        }
        //判断是否删除
        if (!seller.getStatus().equals(0)){
            result.setFailMessage("销售已经删除");
            return  result;
        }
        //设置删除标识
        seller.setStatus(1);
        tbSellerMapper.updateById(seller);
        seller.setUserPass("");
        seller.setPassSalt("");
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("seller",seller);
        result.setResult(hashMap);
        return result;

    }

    @Override
    public ResponseResult setSellerPass(Integer userId, String oldPass, String newPass) {
        ResponseResult result=ResponseResult.SUCCESS();
        //判断销售是否存在
        TbSeller seller = tbSellerMapper.selectById(userId);
        if (seller==null){
            result.setFailMessage("销售不存在");
            return  result;
        }

        String oldPassWord=oldPass+"."+seller.getPassSalt();
        //加密
        String oldMd5Password= DigestUtils.md5DigestAsHex(oldPassWord.getBytes());

        //判断旧密码是否正确
        if (!seller.getUserPass().equals(oldMd5Password)) {
            result.setFailMessage("密码不正确");
            return  result;
        }
        //判断是否删除
        if (!seller.getStatus().equals(0)){
            result.setFailMessage("销售已经删除");
            return  result;
        }
        //加盐
        String password=newPass+"."+seller.getPassSalt();
        //加密
        String md5Password= DigestUtils.md5DigestAsHex(password.getBytes());
        seller.setUserPass(md5Password);
        log.info("pass:"+md5Password);
        //修改密码
        tbSellerMapper.updateById(seller);
        seller.setUserPass("");
        seller.setPassSalt("");
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("seller",seller);
        result.setResult(hashMap);
        return result;
    }


    @Override
    public ResponseResult setSellerInfo(Integer userId, String nickName, String mobile, Integer sex, Integer age, String address) {
        ResponseResult result=ResponseResult.SUCCESS();
        HashMap<String, Object> hashMap = new HashMap<>();
        //判断销售是否存在
        TbSeller seller = tbSellerMapper.selectById(userId);
        if (seller==null){
            result.setFailMessage("销售不存在");
            return  result;
        }
        //判断是否删除
        if (!seller.getStatus().equals(0)){
            result.setFailMessage("销售已经删除");
            return  result;
        }
        seller.setNickName(nickName);
        seller.setMobile(mobile);
        seller.setSex(sex);
        seller.setAge(age);
        seller.setAddress(address);
        //修改销售信息
        tbSellerMapper.updateById(seller);
        //将返回的密码和盐设置为空
        seller.setUserPass("");
        seller.setPassSalt("");
        hashMap.put("seller",seller);
        result.setResult(hashMap);
        return  result;
    }

    @Override
    public ResponseResult doSellerLogin(String userName, String passWord) {
        ResponseResult result=ResponseResult.SUCCESS();
        HashMap<String, Object> hashMap = new HashMap<>();
        TbSeller seller = tbSellerMapper.selectOne(new QueryWrapper<TbSeller>()
                .eq("user_name", userName)
                .eq("status", 0)
                .last("limit 1")
        );
        //判断用户是否存在
        if (seller==null){
            result.setFailMessage("销售不存在");
            return  result;
        }
        //加盐
        String password=passWord+"."+seller.getPassSalt();
        //加密
        String md5Password= DigestUtils.md5DigestAsHex(password.getBytes());
        //判断密码是否相同
        if (!seller.getUserPass().equals(md5Password)) {
            result.setFailMessage("密码不正确");
            return  result;
        }
        //返回值中将盐和密码设为空
        seller.setUserPass("");
        seller.setPassSalt("");
        //生成token
        String token= JwtTokenUtils.makeToken(seller.getId(),seller.getUserName(),"seller");
        //存取数据
        hashMap.put("token",token);
        hashMap.put("seller",seller);
        result.setResult(hashMap);

        //redis单点登陆
        String key = "seller_token_"+seller.getId();
        redisTemplate.opsForValue().set(key, token,1, TimeUnit.DAYS);
        return  result;
    }

    @Override
    public ResponseResult getSellerList(Integer pageCurrent, Integer pageSize) {
        ResponseResult result=ResponseResult.SUCCESS();
        HashMap<String, Object> hashMap = new HashMap<>();

        Page<TbSeller> page = new Page<>(pageCurrent, pageSize);

        //wrapper.select(WfiOpinion.class, i -> !i.getColumn().equals("available"));//排除某个字段
        //wrapper.select(WfiOpinion.class, i -> i.getProperty().endsWith("valid"));//在某个字段结束，包括该字

//        IPage<TbSeller> pages = tbSellerMapper.selectPage(page,
//                new QueryWrapper<TbSeller>()
//                .select("mobile,nick_name,user_name,sex,age,sale_fee,address,status,join_time")
//                );
        IPage<TbSeller> pages = tbSellerMapper.selectPage(
                page,
                new QueryWrapper<TbSeller>()
                .select(TbSeller.class, i -> !i.getColumn().equals("user_pass") && !i.getColumn().equals("pass_salt"))
                .orderByDesc("id")
        );

        hashMap.put("pages", pages);
        result.setResult(hashMap);

        return result;
    }


    /**
    * @Description: getSellerInfo
    * @Param: [sellerId]
    * @return: com.shenmazong.utils.ResponseResult
    * @Author: 亮子说编程
    * @Date: 2020/10/5 19:25
    */
    @Override
    public ResponseResult getSellerInfo(Integer sellerId) {
        ResponseResult result=ResponseResult.SUCCESS();
        HashMap<String, Object> hashMap = new HashMap<>();

        TbSeller tbSeller = tbSellerMapper.selectById(sellerId);
        if(tbSeller == null) {
            result.setFailMessage("销售人员不存在");
            return result;
        }

        hashMap.put("seller", tbSeller);
        result.setResult(hashMap);

        return result;
    }
}
